package com.javaweb.admin.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biz.smpaa.webservice.YsIntfce;
import com.biz.smpaa.webservice.YsUploadReuslt;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.*;
import com.javaweb.admin.query.*;
import com.javaweb.admin.service.Const;
import com.javaweb.admin.service.IYgOrderService;
import com.javaweb.admin.service.SQLDBQuery;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.utils.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.*;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YgOrderServiceImpl implements IYgOrderService {
    @Autowired
    private YgOrderMapper ygOrderMapper;
    @Autowired
    private NCInvoiceMapper ncInvoiceMapper;
    @Autowired
    private NCSaleInvoiceMapper ncSaleInvoiceMapper;
    @Autowired
    private YYq010RsMapper yq010RsMapper;
    @Autowired
    private YYq004RsMapper yq004RsMapper;
    @Autowired
    private YYq004RsDetailMapper yq004RsDetailMapper;
    @Autowired
    private YConverRateMapper converRateMapper;
    @Autowired
    private YgptAddrContrastMapper addrContrastMapper;
    @Autowired
    private NCInvInfoDocMapper invInfoDocMapper;
    @Autowired
    private NCCustInfoDocMapper custInfoDocMapper;
    @Autowired
    private NCCustAddrDocMapper custAddrDocMapper;
    @Autowired
    private NCDispatchingMapper dispatchingMapper;
    @Autowired
    private DinvoiceInfoMapper invoiceInfoMapper;
    @Autowired
    private DinvoiceDetailInfoMapper invoiceDetailInfoMapper;
    @Autowired
    private MInvoicesrelationMapper invoicesrelationMapper;
    @Autowired
    private MInvoicesrelationlineMapper invoicesrelationlineMapper;

    private static final QName SERVICE_NAME = new QName("http://main.service.local.wondersgroup.com/", "YsxtMainServiceImplService");

    @Override
    public JsonResult GetYgOrderList(BaseQuery query) {
        YgOrderQuery ygOrderQuery = (YgOrderQuery) query;

        // 获取数据列表
        if (ygOrderQuery.getPage() == null) {
            ygOrderQuery.setPage(1);
            ygOrderQuery.setLimit(100000);
        }
        String dateBegin = ygOrderQuery.getRiqiBegin();
        dateBegin = dateBegin.substring(0,10);
        String dateEnd = ygOrderQuery.getRiqiEnd();
        dateEnd = dateEnd.substring(0,10);
        dateBegin = DateUtil.format(DateUtils.parseDate(dateBegin), DateUtils.YYYY_MM_DD) + " 00:00:00";
        dateEnd = DateUtil.format(DateUtils.parseDate(dateEnd), DateUtils.YYYY_MM_DD) + " 23:59:59";

        ygOrderQuery.setRiqiBegin(dateBegin);
        ygOrderQuery.setRiqiEnd(dateEnd);
        IPage<YgOrder> page = new Page<>(ygOrderQuery.getPage(), ygOrderQuery.getLimit());
        IPage<YgOrder> pageData = ygOrderMapper.GetYgOrderList(page, ygOrderQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCInvoiceList(BaseQuery query) {
        NCInvoiceQuery invoiceQuery = (NCInvoiceQuery) query;

        // 获取数据列表
        if (invoiceQuery.getPage() == null) {
            invoiceQuery.setPage(1);
            invoiceQuery.setLimit(100000);
        }
        IPage<NCInvoice> page = new Page<>(invoiceQuery.getPage(), invoiceQuery.getLimit());
        IPage<NCInvoice> pageData = ncInvoiceMapper.GetNCInvoiceList(page, invoiceQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCSaleInvoice(String fph) {
        return JsonResult.success(ncSaleInvoiceMapper.GetNCSaleInvoiceList(fph));
    }

    @Override
    public JsonResult GetNC56InvoiceList(BaseQuery query) {
        NCInvoiceQuery invoiceQuery = (NCInvoiceQuery) query;

        // 获取数据列表
        if (invoiceQuery.getPage() == null) {
            invoiceQuery.setPage(1);
            invoiceQuery.setLimit(100000);
        }
        IPage<YYq004RsVo> page = new Page<>(invoiceQuery.getPage(), invoiceQuery.getLimit());
        IPage<YYq004RsVo> pageData = yq004RsMapper.GetYg004List(page, invoiceQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetDispatchDetail(String psdh) {
        List<NCDispatchingDetail> list = dispatchingMapper.GetDispatchDetail(psdh);
        return JsonResult.success(list);
    }

    @Override
    public JsonResult GetNCDispatchingList(BaseQuery query) {
        NCDispatchingQuery dispatchingQuery = (NCDispatchingQuery)query;
        // 获取数据列表
        if (dispatchingQuery.getPage() == null) {
            dispatchingQuery.setPage(1);
            dispatchingQuery.setLimit(100000);
        }
        IPage<NCDispatching> page = new Page<>(dispatchingQuery.getPage(), dispatchingQuery.getLimit());
        IPage<NCDispatching> pageData = dispatchingMapper.GetNCDispatchingList(page, dispatchingQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCInvInfoList(BaseQuery query) {
        NCInvQuery invQuery = (NCInvQuery) query;

        // 获取数据列表
        if (invQuery.getPage() == null) {
            invQuery.setPage(1);
            invQuery.setLimit(100000);
        }
        IPage<NCInvInfoDoc> page = new Page<>(invQuery.getPage(), invQuery.getLimit());
        QueryWrapper<NCInvInfoDoc> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(invQuery.getInvcode()))
        {
            queryWrapper.like("invcode",invQuery.getInvcode());
        }
        if(!StringUtils.isEmpty(invQuery.getInvname()))
        {
            queryWrapper.like("invname",invQuery.getInvname());
        }
        IPage<NCInvInfoDoc> pageData = invInfoDocMapper.selectPage(page, queryWrapper);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCCustInfoList(BaseQuery query) {
        NCCustQuery invQuery = (NCCustQuery) query;

        // 获取数据列表
        if (invQuery.getPage() == null) {
            invQuery.setPage(1);
            invQuery.setLimit(100000);
        }
        IPage<NCCustInfoDoc> page = new Page<>(invQuery.getPage(), invQuery.getLimit());
        QueryWrapper<NCCustInfoDoc> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(invQuery.getCustcode()))
        {
            queryWrapper.like("custcode",invQuery.getCustcode());
        }
        if(!StringUtils.isEmpty(invQuery.getCustname()))
        {
            queryWrapper.like("custname",invQuery.getCustname());
        }
        IPage<NCCustInfoDoc> pageData = custInfoDocMapper.selectPage(page, queryWrapper);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCCustAddrList(BaseQuery query) {
        NCCustQuery invQuery = (NCCustQuery) query;

        // 获取数据列表
        if (invQuery.getPage() == null) {
            invQuery.setPage(1);
            invQuery.setLimit(100000);
        }
        IPage<NCCustAddrDoc> page = new Page<>(invQuery.getPage(), invQuery.getLimit());
        QueryWrapper<NCCustAddrDoc> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(invQuery.getCustcode()))
        {
            queryWrapper.like("custcode",invQuery.getCustcode());
        }
        if(!StringUtils.isEmpty(invQuery.getCustname()))
        {
            queryWrapper.like("custname",invQuery.getCustname());
        }
        if(!StringUtils.isEmpty(invQuery.getCustaddr()))
        {
            queryWrapper.like("addrname",invQuery.getCustaddr());
        }
        IPage<NCCustAddrDoc> pageData = custAddrDocMapper.selectPage(page, queryWrapper);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetNCInvList(BaseQuery query) {
        String sql = "select  distinct invcode, invname, measname, invspec,hsl, sccj  from "+CommonConfig.ncInvInfo+"  where   nvl(dr,0) =0";
        NCInvQuery invQuery = (NCInvQuery)query;
        if(!StringUtils.isEmpty(invQuery.getInvcode()))
        {
            sql += " and invcode  like '%"+invQuery.getInvcode()+"%'";
        }
        if(!StringUtils.isEmpty(invQuery.getInvname()))
        {
            sql += " and invname  like '%"+invQuery.getInvname()+"%'";
        }
        try {
            return JsonResult.success(DBUtils.convertList(DBUtils.GetResultSet(sql)));
        } catch (SQLException throwables) {
            return JsonResult.error("无法获取NC存货编码,请重试导入或者在NC系统增加存货对照信息。");
        }
    }

    @Override
    public JsonResult GetNC56InvList(BaseQuery query) {
        String sql = "select  * from v_nc_invlist where 1=1";
        NCInvQuery invQuery = (NCInvQuery)query;
        if(!StringUtils.isEmpty(invQuery.getInvcode()))
        {
            sql += " and invcode  like '%"+invQuery.getInvcode()+"%'";
        }
        if(!StringUtils.isEmpty(invQuery.getInvname()))
        {
            sql += " and invname  like '%"+invQuery.getInvname()+"%'";
        }
        try {
            return JsonResult.success(SQLUtils.convertList(SQLUtils.GetResultSet(sql)));
        } catch (SQLException throwables) {
            return JsonResult.error("无法获取NC存货编码,请重试导入或者在NC系统增加存货对照信息。");
        }
    }
    @Override
    public JsonResult GetNCCustList(BaseQuery query) {
        String sql = "select distinct custcode, custname, detailinfo, pk_address  from "+CommonConfig.ncCustAddr+"   where ( email <> '@' or email is null ) and nvl(ADDR_DR,0) =0 and nvl(custaddr_dr,0) =0";
        NCCustQuery custQuery = (NCCustQuery)query;
        if(!StringUtils.isEmpty(custQuery.getCustcode()))
        {
            sql += " and custcode  like '%"+custQuery.getCustcode()+"%'";
        }
        if(!StringUtils.isEmpty(custQuery.getCustname()))
        {
            sql += " and custname  like '%"+custQuery.getCustname()+"%'";
        }
        if(!StringUtils.isEmpty(custQuery.getCustaddr()))
        {
            sql += " and detailinfo  like '%"+custQuery.getCustaddr()+"%'";
        }
        if(StringUtils.isEmpty(custQuery.getCustcode()) && StringUtils.isEmpty(custQuery.getCustname()) && StringUtils.isEmpty(custQuery.getCustaddr()))
        {
            sql+=" and custname=''";
        }
        try {
            return JsonResult.success(DBUtils.convertList(DBUtils.GetResultSet(sql)));
        } catch (SQLException throwables) {
            return JsonResult.error("无法获取NC客户信息，请重试或者确定您的网络连接。");
        }
    }

    @Override
    public JsonResult GetNC56CustList(BaseQuery query) {
        String sql = "select * from v_nc_custlist where 1=1";
        NCCustQuery custQuery = (NCCustQuery)query;
        if(!StringUtils.isEmpty(custQuery.getCustcode()))
        {
            sql += " and custcode  like '%"+custQuery.getCustcode()+"%'";
        }
        if(!StringUtils.isEmpty(custQuery.getCustname()))
        {
            sql += " and custname  like '%"+custQuery.getCustname()+"%'";
        }
        if(!StringUtils.isEmpty(custQuery.getCustaddr()))
        {
            sql += " and addrname  like '%"+custQuery.getCustaddr()+"%'";
        }
        if(StringUtils.isEmpty(custQuery.getCustcode()) && StringUtils.isEmpty(custQuery.getCustname()) && StringUtils.isEmpty(custQuery.getCustaddr()))
        {
            sql+=" and custname=''";
        }
        try {
            return JsonResult.success(SQLUtils.convertList(SQLUtils.GetResultSet(sql)));
        } catch (SQLException throwables) {
            return JsonResult.error("无法获取NC客户信息，请重试或者确定您的网络连接。");
        }
    }

    @Override
    public JsonResult GetYConverRateList(BaseQuery query) {
        YConverRateQuery converRateQuery = (YConverRateQuery) query;

        // 获取数据列表
        if (converRateQuery.getPage() == null) {
            converRateQuery.setPage(1);
            converRateQuery.setLimit(100000);
        }
        IPage<YConverRate> page = new Page<>(converRateQuery.getPage(), converRateQuery.getLimit());
        IPage<YConverRate> pageData = converRateMapper.GetYConverRateList(page, converRateQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult GetYgptAddrContrastList(BaseQuery query) {
        YgptAddrContrastQuery contrastQuery = (YgptAddrContrastQuery) query;

        // 获取数据列表
        if (contrastQuery.getPage() == null) {
            contrastQuery.setPage(1);
            contrastQuery.setLimit(100000);
        }
        IPage<YgptAddrContrast> page = new Page<>(contrastQuery.getPage(), contrastQuery.getLimit());
        IPage<YgptAddrContrast> pageData = addrContrastMapper.GetYgptAddrContrastList(page, contrastQuery);
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult UpdateInvCode(YConverRate entity) {
        try
        {
            SQLDBQuery.setConverRateValue(entity.getConverrate(),entity.getZxspbm(),entity.getConverratetype(),entity.getInvcode(),entity.getInvname(),1,"");
            return JsonResult.success();
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult UpdateCustAddr(YgptAddrContrast entity) {
        try
        {
            SQLDBQuery.setYgCustAddrInfo(entity.getId(),entity.getCustaddrname(),entity.getYwy(),entity.getCustcode(),entity.getCustname(),entity.getPkcustaddr(),entity.getErpwarehouse());
            return JsonResult.success();
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    private void updateYgOrderStateByDDMXB(String orderDetailIDOrigin, String flag) {
        UpdateWrapper<YYq010Rs> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("imperpflag", flag).eq("ddmxbh", orderDetailIDOrigin);
        yq010RsMapper.update(new YYq010Rs(), updateWrapper);
    }

    private String FormatNC63NodeBody(String data) {
        return "<item>" + data + "</item>";
    }

    private String PostXmlToNC63SaleOrder(String postData) throws Exception {
        BasicHttpClientConnectionManager connManager;
        connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        String url = CommonConfig.ncServiceUrl;
        HttpRequestBase httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10 * 1000).setConnectTimeout(10 * 1000).build();
        httpPost.setConfig(requestConfig);

        if (!StringUtils.isEmpty(postData)) {
            StringEntity postEntity = new StringEntity(postData, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            //httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
            ((HttpPost) httpPost).setEntity(postEntity);
        }

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, "UTF-8");

    }

    private String PostDataToNC63forYS(String doc,List<String> orderImportRowNum,String orderIDOrigin, boolean getImpXml, String startDate)
    {
        String retVal = "";
        String result = "";
        try {
            FileUtils.writeLog("导入NC63XML",doc);
            result = PostXmlToNC63SaleOrder(doc);
            FileUtils.writeLog("导入NC63XML","NC63反馈导入结束>>>>>>>>>>>>>>");
            FileUtils.writeLog("导入NC63XML",result);

            Document document= XmlUtil.readXML(result);
            Element elementG=XmlUtil.getRootElement(document);
            if(elementG.getAttribute("successful").equals("Y"))
            {
                for (int i = 0; i < orderImportRowNum.size(); i++) {
                    updateYgOrderStateByDDMXB(orderImportRowNum.get(i),"已导入");
                }
            }
            else
            {
                Element elementResult = XmlUtil.getElement(elementG,"sendresult");
//                String description = elementResult.getElementsByTagName("resultdescription").item(0).getTextContent();
                String description = CommonUtils.XmlGetNodeContent(elementResult,"resultdescription");
                retVal = orderIDOrigin+"导入出错:"+description;
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                FileUtils.writeLog("导入NC63XML",orderIDOrigin + "导入出错。" + "result="+  result + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        return retVal;
    }

    @Override
    //@SpecifyDataSource(value = DataSourceType.NC63)
    public JsonResult ExportToNC(YgOrderDto dto) {
        //将选择的单据号提交至NC
        String customerCode = "";//ERP销售订单客户编码
        String orderCustName = "";//ERP订单客户名称
        String billCustcode = "";//ERP开票客户编码
        String erpInvcode = ""; //ERP存货编码
        String orderIDOrigin = "";//计划单号
        String orderDetailIDOrigin = "";//订单明细编号
        String ZXSPBM = "";//统编代码
        String PSDBM = "";//配送点编码
        String ygptAddressName = "";//配送地址名称
        String YYBM = "";//医院编码
        String customerName = "";//医院名称
        String impErpState = "";//导入ERP状态
        String CPM = "";//药品名称
        String CFGG = "";//成分规格
        String errorMeg = "";//异常信息
        String deptcode = "";//部门编码
        String psncode = "";//业务员编码,业务员根据地址指定 Y_YgptAddrContrast.ywy
        String custGpoArea = "";//NC63客户属性绑定的GPO区域
        String nc63_Order_type = "";//NC63销售订单类型{普通销售orGPO销售}
        String nc63_Busitype = ""; //NC63销售业务类型{ 信谊雷允上普通销售 or 信谊雷允上GPO销售}
        String DDTJRQ = "";//外部平台订单日期
        String custaddrname = "";//ERP仓库地址
        BigDecimal yycgj;//医院采购价
        BigDecimal CGSL;//采购数量

        //临时比较ID
        String orderIDOriginPrev = "";
        String orderTypePrve = "";
        String customerNamePrev = "";
        String customerCodePrev = "";

        boolean gpoFlag;//当前订单行是否GPO价格
        String fpMemo = "";//开发票的备注内容。部分总分院的，要求开票备注栏显示总院的名称。通过订单传递到发票
        //计划单号会和历史的计划单号纯在相同的，加入当前查询开始日期。不去检查历史的计划单号
        String startDate = dto.getStartDate();
        String[] ddmxbhs = dto.getDdmxbhs();
        List<String> orderFail = new ArrayList<>();
        List<String> orderSuccess = new ArrayList<>();
        List<String> orderImportRowNum = new ArrayList<>();

        ClassPathResource classPathResource = new ClassPathResource("nc/SalesOrderNC63.xml");
        InputStream inputStream = classPathResource.getStream();
        //File soNC63 = IoUtil.readUtf8(inputStream);
        Document document= XmlUtil.readXML(inputStream);
        Element elementG=XmlUtil.getRootElement(document);
        Element elementBill =XmlUtil.getElement(elementG,"bill");
        Element elementHead =XmlUtil.getElement(elementBill,"billhead");
        Element elementDetail =XmlUtil.getElement(elementHead,"so_saleorder_b");
        Node nodeOrderItem = elementDetail.getFirstChild();
        Element elementBody =XmlUtil.getElement(elementDetail,"item");

        YgOrder entity;
        //遍历选择的阳光订单，完成数据检查
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                //初始化
                fpMemo = "";
                customerCode = "";
                orderCustName = "";
                billCustcode = "";
                deptcode = "";
                psncode = "";
                erpInvcode = "";
                //errorMeg = "";
                nc63_Order_type = "";
                nc63_Busitype = "";
                System.out.println(ddmxbhs[i]);
                entity = ygOrderMapper.selectList(new QueryWrapper<YgOrder>().eq("ddmxbh", ddmxbhs[i])).get(0);
                orderIDOrigin = entity.getJhdh();
                orderDetailIDOrigin = entity.getDdmxbh();
                impErpState = entity.getImperpflag();
                CPM = entity.getCpm();
                CFGG = entity.getCfgg();
//                if (CFGG.startsWith("1g*")) {
//                    CFGG = CFGG.replace("1g*", "");
//                }
                ZXSPBM = entity.getZxspbm();
                PSDBM = entity.getPsdbm();
                YYBM = entity.getYybm();
                customerName = entity.getYymc();
                ygptAddressName = entity.getPsdz();
                DDTJRQ = entity.getDdtjrq();
                custaddrname = entity.getCustaddrname();
                custGpoArea = ""; //初始化GPO区域
                gpoFlag = false;//初始化GPO
                yycgj = entity.getCgjg();
                CGSL = entity.getCgsl();
                BigDecimal quantity = CGSL;
                if ("无货回传".equals(impErpState)) {
                    errorMeg = errorMeg + "\n" + "医院：【" + customerName + "】【" + CPM + "】订单【" + orderDetailIDOrigin + "】已设置为【" + impErpState + "】，不允许导入！ ";
                    continue;
                }
//                if(StringUtils.isEmpty(entity.getXylx()))
//                {
//                    errorMeg = errorMeg + "\n" + "医院：【" + customerName + "】【" + CPM + "】订单【" + orderDetailIDOrigin + "】尚未响应，不允许导入！ ";
//                    continue;
//                }else {
//                    if(Const.ORDER_RESPONSE_NO.equals(entity.getXylx()))
//                    {
//                        errorMeg = errorMeg + "\n" + "医院：【" + customerName + "】【" + CPM + "】订单【" + orderDetailIDOrigin + "】响应类型【"+Const.ORDER_RESPONSE_NO+"】，不允许导入！ ";
//                        continue;
//                    }
//                }
                if (SQLDBQuery.GetNC63SalesOrderByExternaOrderIDAndMedicCodeIsExistYs(orderDetailIDOrigin)) {
                    //已存在情况下，更新订单状态为“已导入”

                    if (!"已导入".equals(impErpState) && !"无货回传".equals(impErpState)) {
                        updateYgOrderStateByDDMXB(orderDetailIDOrigin, "已导入");
                    }
                    errorMeg = errorMeg + "\n" + "医院：【" + customerName + "】【" + CPM + "】订单【" + orderDetailIDOrigin + "】已存在 ";
                    continue;

                } else {
                    if (!"无货回传".equals(impErpState)) {
                        if ("已导入".equals(impErpState)) {
                            updateYgOrderStateByDDMXB(orderDetailIDOrigin, "未导入");
                        }
                    }
                    if ("无货回传".equals(impErpState)) {
                        errorMeg = errorMeg + "\n" + "医院：【" + customerName + "】【" + CPM + "】订单【" + orderDetailIDOrigin + "】已设置为【" + impErpState + "】，不允许导入！ ";
                        continue;
                    }
                }
                //获取客户信息{客户编码、开票客户编码、送货地址、部门、人员}
                //同一医院不同地址不同业务员元的，根据地址表取人员，未维护的取客户设置的默认业务员
                String pk_address = "";
                String erpwarehouse = "";
                List<HashMap> customerDt = SQLDBQuery.getCustInfoByYYBM(YYBM, PSDBM);
                if (customerDt.size() > 0 && !StringUtils.isNullOrEmpty(customerDt.get(0).get("custaddrname"))) {
                    customerCode = customerDt.get(0).get("custcode").toString().trim();
                    erpwarehouse = customerDt.get(0).get("erpwarehouse").toString().trim();
                    orderCustName = customerDt.get(0).get("custname").toString();
                    billCustcode = customerDt.get(0).get("billCustcode").toString();
                    deptcode = customerDt.get(0).get("deptcode").toString();
                    psncode = customerDt.get(0).get("psncode").toString();
                    //ygptAddressName = customerDt.Rows[0]["custaddrname"].ToString();
                    custGpoArea = customerDt.get(0).get("gpoarea").toString();
                    fpMemo = customerDt.get(0).get("fpmemo") == null ? "" : customerDt.get(0).get("fpmemo").toString();
                    pk_address = SQLDBQuery.getNC63CustAddrPk(customerCode, custaddrname);

                }
                if (StringUtils.isEmpty(pk_address)) {
                    //throw new ApplicationException("未能在ERP系统【基础数据对照表】-【雷允上对照药事所-客户档案】中到找对应客户信息，请确认是否维护外部系统值（" + customerCodeExternal + "对应客户编码）！");
                    errorMeg = errorMeg + "\n" + "未在【医院及配送地址对照】中找到对应客户信息，请确认是否维护医院和地址对照（" + YYBM + "#" + PSDBM + "对应客户编码和地址。 或者NC63地址已更新，请重新维护对照。）！";
                    continue;
                }
                if (StringUtils.isEmpty(erpwarehouse)) {
                    //throw new ApplicationException("未能在ERP系统【基础数据对照表】-【雷允上对照药事所-客户档案】中到找对应客户信息，请确认是否维护外部系统值（" + customerCodeExternal + "对应客户编码）！");
                    errorMeg = errorMeg + "\n" + "未在【医院及配送地址对照】中找到客户对应的EPR出库仓库，请确认是否维护医院和ERP出库仓库对照（" + YYBM + "#" + PSDBM + "对应NC出库仓库。";
                    continue;
                }

                ConverRate invConverVo = SQLDBQuery.getInvConverRateByZXSPBM(ZXSPBM, CFGG);
                if (invConverVo != null && !StringUtils.isNullOrEmpty(invConverVo.getInvcode())) {
                    if (invConverVo.getInvalidFlag()) {
                        errorMeg = errorMeg + "\n" + "该（" + CPM + "_" + ZXSPBM + "_" + CFGG + "）医保代码已经作废,作废说明【" + invConverVo.getInvalidMemo() + "】！";
                        continue;
                    }
                    erpInvcode = invConverVo.getInvcode().trim();
                } else {
                    errorMeg = errorMeg + "\n" + "【产品及规格对照】中未找到对应产品信息或产品转换率未设置，请确认是否维护该产品和规格单位对照（" + CPM + "_" + ZXSPBM + "_" + CFGG + "）！";
                    continue;
                }

                if (ZXSPBM.substring(0, 1).equals("T")) {
                    CommonUtils.XmlSetNodeContent(elementHead, "cdeptvid", "5020");
                    CommonUtils.XmlSetNodeContent(elementHead, "cdeptid", "5020");
                    CommonUtils.XmlSetNodeContent(elementHead, "cemployeeid", "228178A");
                } else {
                    CommonUtils.XmlSetNodeContent(elementHead, "cdeptvid", deptcode);
                    CommonUtils.XmlSetNodeContent(elementHead, "cdeptid", deptcode);
                    CommonUtils.XmlSetNodeContent(elementHead, "cemployeeid", psncode);
                }
                //制单人
                CommonUtils.XmlSetNodeContent(elementHead, "billmaker", "1233_998");
                CommonUtils.XmlSetNodeContent(elementHead, "creator", "1233_998");
                //客户编码
                CommonUtils.XmlSetNodeContent(elementHead, "ccustomerid", customerCode);
                //开票客户编码
                CommonUtils.XmlSetNodeContent(elementHead, "cinvoicecustid", billCustcode);
                //地址传递至ERP,地址取地址簿的主键ID
                CommonUtils.XmlSetNodeContent(elementHead, "vdef1", pk_address);

                CommonUtils.XmlSetNodeContent(elementHead, "dbilldate", DateUtil.now());
                CommonUtils.XmlSetNodeContent(elementHead, "dmakedate", DateUtil.now());
                if ("传总院名".equals(fpMemo)) {
                    CommonUtils.XmlSetNodeContent(elementHead, "vnote", orderCustName);
                } else {
                    CommonUtils.XmlSetNodeContent(elementHead, "vnote", "");
                }
                //处理表体数据
                CommonUtils.XmlSetNodeContent(elementBody, "dbilldate", DateUtil.now());
                //物料编码
                CommonUtils.XmlSetNodeContent(elementBody, "cmaterialvid", erpInvcode);
                CommonUtils.XmlSetNodeContent(elementBody, "cmaterialid", erpInvcode);
                //主计量单位 不写入，系统默认为产品对应的主单位
                CommonUtils.XmlSetNodeContent(elementBody, "cunitid", invConverVo.getMeascode());
                CommonUtils.XmlSetNodeContent(elementBody, "cqtunitid", invConverVo.getMeascode());
                CommonUtils.XmlSetNodeContent(elementBody, "castunitid", invConverVo.getMeascode());

                //税率的税编号
                CommonUtils.XmlSetNodeContent(elementBody, "ctaxcodeid", invConverVo.getTaxratcode());
                //税率值
                CommonUtils.XmlSetNodeContent(elementBody, "ntaxrate", invConverVo.getTaxratio());
                //含税单价 init
                BigDecimal priceTax = BigDecimal.ZERO;
                BigDecimal taxRate = new BigDecimal(invConverVo.getTaxratio());
                String cchannelCode = "";

                List<HashMap> gpoPriceDt = SQLDBQuery.getNc63PriceByGpo(customerCode, erpInvcode, custGpoArea);
                if (gpoPriceDt.size() > 0) {
                    if (!StringUtils.isNullOrEmpty(gpoPriceDt.get(0).get("nprice1"))) {
                        priceTax = new BigDecimal(gpoPriceDt.get(0).get("nprice1").toString());

                        String gpoareaname = gpoPriceDt.get(0).get("gpoareaname").toString();
                        if ("上海地区".equals(gpoareaname)) {
                            nc63_Order_type = Const.SALES_ORDER_TYPE_GPO_2;
                            nc63_Busitype = Const.SALE_ORDER_BUSITYPE_GPO_2;
                        } else {
                            nc63_Order_type = Const.SALES_ORDER_TYPE_PUTONG;
                            nc63_Busitype = Const.SALE_ORDER_BUSITYPE_PUTONG;
                        }
                        cchannelCode =StringUtils.isNullOrEmpty(gpoPriceDt.get(0).get("channelcode"))?"": gpoPriceDt.get(0).get("channelcode").toString();

                    }
                }
                //priceTax<=0
                if (priceTax.compareTo(BigDecimal.ZERO)<=0) {
                    //未能获取NC63价格，请联系价格维护人员
                    errorMeg = errorMeg + "\n" + "订单【" + customerName + "_" + customerCode + "】对应产品： 【" + CPM + "】 【" + ZXSPBM + "】【" + erpInvcode + "】询价失败，请联系价格维护人员再执行导入ERP";
                    continue;
                }

                //>>>>>>>>>>>>>>订单数量转换处理， 获取统编代码对应的规格单位转换关系
                if (invConverVo == null || StringUtils.isNullOrEmpty(invConverVo.getConverRate())) {
                    //未设置改统编代码的规格单位转换率，提醒需要设置
                    //throw new Exception("订单【" + customerName + "】对应产品： 【" + CPM + "】 【" + ygptInvode + "】未设置规格单位转换，请设置后再执行导入ERP");
                    errorMeg = errorMeg + "\n" + "订单【" + customerName + "】对应产品： 【" + CPM + "】 【" + ZXSPBM + "】未设置规格单位转换，请设置后再执行导入ERP";
                    continue;
                } else {
                    BigDecimal rate = new BigDecimal(invConverVo.getConverRate());
                    if ("乘".equals(invConverVo.getConverRateType())) {
                        quantity = quantity.multiply(rate);
                        yycgj = yycgj.divide(rate,6,RoundingMode.HALF_UP);


                    } else if ("除".equals(invConverVo.getConverRateType())) {
                        quantity = quantity.divide(rate,6,RoundingMode.HALF_UP);
                        yycgj = yycgj.multiply(rate);
                    } else {
                        //throw new Exception("订单【" + customerName + "】对应产品： 【" + CPM + "】 【" + ygptInvode + "】未设置规格单位转换，请设置后再执行导入ERP");
                        errorMeg = errorMeg + "\n" + "订单【" + customerName + "】对应产品： 【" + CPM + "】 【" + ZXSPBM + "】未设置规格单位转换，请设置后再执行导入ERP";
                        continue;
                    }
                }
                //价格处理>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>END


                //医院采购价同雷允上价格体系不对的，不能开单
                if (yycgj.subtract(priceTax).setScale(2,BigDecimal.ROUND_HALF_UP) != BigDecimal.ZERO.setScale(2)) {
                    errorMeg = errorMeg + "\n" + "当前医院订单【" + customerName + "】对应产品： 【" + CPM + "】【" + erpInvcode + "】 【" + ZXSPBM + "】的采购价【" + yycgj + "】同雷允上的开票价【" + priceTax + "】不一致，无法导入ERP";
                    continue;
                }
            }
            catch(Exception ex)
            {
                orderFail.add(ddmxbhs[i]);
            }
        }
        //如果检查结果有错误，则返回错误信息
        if(!StringUtils.isEmpty(errorMeg))
        {
            return JsonResult.error(errorMeg);
        }
        String message = "";
        try {
            //提交接口的XML文档
            Document docSubmit = null;
            for (int i = 0; i < ddmxbhs.length; i++) {
                try {
                    //初始化
                    fpMemo = "";
                    customerCode = "";
                    orderCustName = "";
                    billCustcode = "";
                    deptcode = "";
                    psncode = "";
                    erpInvcode = "";
                    //errorMeg = "";
                    nc63_Order_type = "";
                    nc63_Busitype = "";
                    entity = ygOrderMapper.selectList(new QueryWrapper<YgOrder>().eq("ddmxbh", ddmxbhs[i])).get(0);
                    orderIDOrigin = entity.getJhdh();
                    orderDetailIDOrigin = entity.getDdmxbh();
                    impErpState = entity.getImperpflag();
                    CPM = entity.getCpm();
                    CFGG = entity.getCfgg();
//                if (CFGG.startsWith("1g*")) {
//                    CFGG = CFGG.replace("1g*", "");
//                }
                    ZXSPBM = entity.getZxspbm();
                    PSDBM = entity.getPsdbm();
                    YYBM = entity.getYybm();
                    customerName = entity.getYymc();
                    ygptAddressName = entity.getPsdz();
                    DDTJRQ = entity.getDdtjrq();
                    custaddrname = entity.getCustaddrname();
                    custGpoArea = ""; //初始化GPO区域
                    gpoFlag = false;//初始化GPO
                    yycgj = entity.getCgjg();
                    CGSL = entity.getCgsl();
                    BigDecimal quantity = CGSL;
                    //获取客户信息{客户编码、开票客户编码、送货地址、部门、人员}
                    //同一医院不同地址不同业务员元的，根据地址表取人员，未维护的取客户设置的默认业务员
                    String pk_address = "";
                    String erpwarehouse = "";
                    List<HashMap> customerDt = SQLDBQuery.getCustInfoByYYBM(YYBM, PSDBM);
                    if (customerDt.size() > 0 && !StringUtils.isEmpty(customerDt.get(0).get("custaddrname").toString())) {
                        customerCode = customerDt.get(0).get("custcode").toString().trim();
                        erpwarehouse = customerDt.get(0).get("erpwarehouse").toString().trim();
                        orderCustName = customerDt.get(0).get("custname").toString();
                        billCustcode = customerDt.get(0).get("billCustcode").toString();
                        deptcode = customerDt.get(0).get("deptcode").toString();
                        psncode = customerDt.get(0).get("psncode").toString();
                        //ygptAddressName = customerDt.Rows[0]["custaddrname"].ToString();
                        custGpoArea = customerDt.get(0).get("gpoarea").toString();
                        fpMemo = customerDt.get(0).get("fpmemo") == null ? "" : customerDt.get(0).get("fpmemo").toString();
                        pk_address = SQLDBQuery.getNC63CustAddrPk(customerCode, custaddrname);

                    }
                    ConverRate invConverVo = SQLDBQuery.getInvConverRateByZXSPBM(ZXSPBM, CFGG);
                    if (invConverVo != null && !StringUtils.isEmpty(invConverVo.getInvcode())) {
                        erpInvcode = invConverVo.getInvcode().trim();
                    }

                    if (ZXSPBM.substring(0, 1).equals("T")) {
                        CommonUtils.XmlSetNodeContent(elementHead, "cdeptvid", "5020");
                        CommonUtils.XmlSetNodeContent(elementHead, "cdeptid", "5020");
                        CommonUtils.XmlSetNodeContent(elementHead, "cemployeeid", "228178A");
                    } else {
                        CommonUtils.XmlSetNodeContent(elementHead, "cdeptvid", deptcode);
                        CommonUtils.XmlSetNodeContent(elementHead, "cdeptid", deptcode);
                        CommonUtils.XmlSetNodeContent(elementHead, "cemployeeid", psncode);
                    }
                    //制单人
                    CommonUtils.XmlSetNodeContent(elementHead, "billmaker", "1233_998");
                    CommonUtils.XmlSetNodeContent(elementHead, "creator", "1233_998");
                    //客户编码
                    CommonUtils.XmlSetNodeContent(elementHead, "ccustomerid", customerCode);
                    //开票客户编码
                    CommonUtils.XmlSetNodeContent(elementHead, "cinvoicecustid", billCustcode);
                    //地址传递至ERP,地址取地址簿的主键ID
                    CommonUtils.XmlSetNodeContent(elementHead, "vdef1", pk_address);

                    CommonUtils.XmlSetNodeContent(elementHead, "dbilldate", DateUtil.now());
                    CommonUtils.XmlSetNodeContent(elementHead, "dmakedate", DateUtil.now());
                    if ("传总院名".equals(fpMemo)) {
                        CommonUtils.XmlSetNodeContent(elementHead, "vnote", orderCustName);
                    } else {
                        CommonUtils.XmlSetNodeContent(elementHead, "vnote", "");
                    }
                    //处理表体数据
                    CommonUtils.XmlSetNodeContent(elementBody, "dbilldate", DateUtil.now());
                    //物料编码
                    CommonUtils.XmlSetNodeContent(elementBody, "cmaterialvid", erpInvcode);
                    CommonUtils.XmlSetNodeContent(elementBody, "cmaterialid", erpInvcode);
                    //主计量单位 不写入，系统默认为产品对应的主单位
                    CommonUtils.XmlSetNodeContent(elementBody, "cunitid", invConverVo.getMeascode());
                    CommonUtils.XmlSetNodeContent(elementBody, "cqtunitid", invConverVo.getMeascode());
                    CommonUtils.XmlSetNodeContent(elementBody, "castunitid", invConverVo.getMeascode());

                    //税率的税编号
                    CommonUtils.XmlSetNodeContent(elementBody, "ctaxcodeid", invConverVo.getTaxratcode());
                    //税率值
                    CommonUtils.XmlSetNodeContent(elementBody, "ntaxrate", invConverVo.getTaxratio());
                    //含税单价 init
                    BigDecimal priceTax = BigDecimal.ZERO;
                    BigDecimal taxRate = new BigDecimal(invConverVo.getTaxratio());
                    String cchannelCode = "";

                    List<HashMap> gpoPriceDt = SQLDBQuery.getNc63PriceByGpo(customerCode, erpInvcode, custGpoArea);
                    if (gpoPriceDt.size() > 0) {
                        if (gpoPriceDt.get(0).get("nprice1") != null) {
                            priceTax = new BigDecimal(gpoPriceDt.get(0).get("nprice1").toString());

                            String gpoareaname = gpoPriceDt.get(0).get("gpoareaname").toString();
                            if ("上海地区".equals(gpoareaname)) {
                                nc63_Order_type = Const.SALES_ORDER_TYPE_GPO_2;
                                nc63_Busitype = Const.SALE_ORDER_BUSITYPE_GPO_2;
                            } else {
                                nc63_Order_type = Const.SALES_ORDER_TYPE_PUTONG;
                                nc63_Busitype = Const.SALE_ORDER_BUSITYPE_PUTONG;
                            }
                            cchannelCode = gpoPriceDt.get(0).get("channelcode") == null ? "" : gpoPriceDt.get(0).get("channelcode").toString();

                        }
                    }
                    BigDecimal rate = new BigDecimal(invConverVo.getConverRate());
                    if ("乘".equals(invConverVo.getConverRateType())) {
                        quantity = quantity.multiply(rate).setScale(5);
                        yycgj = yycgj.divide(rate,6,RoundingMode.HALF_UP);


                    } else if ("除".equals(invConverVo.getConverRateType())) {
                        quantity = quantity.divide(rate,5,RoundingMode.HALF_UP);
                        yycgj = yycgj.multiply(rate);
                    }
                    //价格处理>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>END
                    //医院采购价同雷允上价格体系不对的，不能开单
                    BigDecimal bdRate = taxRate.divide(BigDecimal.valueOf(100).setScale(6)).add(BigDecimal.ONE);
                    BigDecimal priceNet = priceTax.divide(bdRate, 6, BigDecimal.ROUND_HALF_UP);
                    //表头订单类型确认
                    CommonUtils.XmlSetNodeContent(elementHead, "ctrantypeid", nc63_Order_type);
                    CommonUtils.XmlSetNodeContent(elementHead, "vtrantypecode", nc63_Order_type);
                    CommonUtils.XmlSetNodeContent(elementHead, "cbiztypeid", nc63_Busitype);
                    CommonUtils.XmlSetNodeContent(elementHead, "cchanneltypeid", cchannelCode);
                    //数据传入
                    CommonUtils.XmlSetNodeContent(elementBody, "nnum", quantity.toString());
                    CommonUtils.XmlSetNodeContent(elementBody, "nastnum", quantity.toString());

                    //无税金额
                    BigDecimal amountNet = priceNet.multiply(quantity).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //含税金额
                    BigDecimal amountTax = priceTax.multiply(quantity).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //税额
                    BigDecimal tax = amountTax.subtract(amountNet);
                    //含税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtorigtaxprice", priceTax.toString());
                    //无税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtorigprice", priceNet.toString());
                    //含税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtorigtaxnetprc", priceTax.toString());
                    //无税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtorignetprice", priceNet.toString());
                    //主含税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "norigtaxprice", priceTax.toString());
                    //主无税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "norigprice", priceNet.toString());
                    //主含税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "norigtaxnetprice", priceTax.toString());
                    //主无税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "norignetprice", priceNet.toString());
                    //税额
                    CommonUtils.XmlSetNodeContent(elementBody, "ntax", tax.toString());
                    //计税金额 = 含税总额
                    CommonUtils.XmlSetNodeContent(elementBody, "ncaltaxmny", amountTax.toString());
                    //无税金额
                    CommonUtils.XmlSetNodeContent(elementBody, "norigmny", amountNet.toString());
                    //价税合计 = 含税总额
                    CommonUtils.XmlSetNodeContent(elementBody, "norigtaxmny", amountTax.toString());
                    //本币含税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqttaxprice", priceTax.toString());
                    //本币无税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtprice", priceNet.toString());
                    //本币含税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqttaxnetprice", priceTax.toString());
                    //本币无税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "nqtnetprice", priceNet.toString());
                    //主本币含税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "ntaxprice", priceTax.toString());
                    //主本币无税单价
                    CommonUtils.XmlSetNodeContent(elementBody, "nprice", priceNet.toString());
                    //主本币含税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "ntaxnetprice", priceTax.toString());
                    //主本币无税净价
                    CommonUtils.XmlSetNodeContent(elementBody, "nnetprice", priceNet.toString());
                    //本币无税金额
                    CommonUtils.XmlSetNodeContent(elementBody, "nmny", amountNet.toString());
                    //本币价税合计 = 含税总额
                    CommonUtils.XmlSetNodeContent(elementBody, "ntaxmny", amountTax.toString());
                    //要求发货日期
                    CommonUtils.XmlSetNodeContent(elementBody, "dsenddate", DateUtil.now());
                    //计划到货日期
                    CommonUtils.XmlSetNodeContent(elementBody, "dreceivedate", DateUtil.now());
                    //收货客户
                    CommonUtils.XmlSetNodeContent(elementBody, "creceivecustid", customerCode);
                    //收货地址
                    CommonUtils.XmlSetNodeContent(elementBody, "creceiveaddrid", ygptAddressName);

                    CommonUtils.XmlSetNodeContent(elementBody, "vbdef5", orderDetailIDOrigin);
                    CommonUtils.XmlSetNodeContent(elementBody, "vbdef8", orderDetailIDOrigin);
                    //外部平台来源标志 vdef9: Yaoshi
                    CommonUtils.XmlSetNodeContent(elementBody, "vbdef9", Const.SALE_ORDER_SOURCE_YS);
                    if (!StringUtils.isEmpty(entity.getGeyinflag())) {
                        if ("1".equals(entity.getGeyinflag().trim())) {
                            CommonUtils.XmlSetNodeContent(elementBody, "vbdef9", Const.SALE_ORDER_SOURCE_GY);
                        }
                    }
                    //外部平台产品编码
                    CommonUtils.XmlSetNodeContent(elementBody, "vbdef10", ZXSPBM);
                    CommonUtils.XmlSetNodeContent(elementBody, "vbdef11", PSDBM);
                    CommonUtils.XmlSetNodeContent(elementBody, "crowno", String.valueOf(i + 1));
                    //更新模板中的出库仓库
                    CommonUtils.XmlSetNodeContent(elementBody, "csendstordocid", erpwarehouse);

                    //是否合单导入（同客户+地址+GPO）or （同客户+地址+非GPO）
                    String customerCodeExternal = YYBM + "#" + PSDBM + "#" + gpoFlag;
                    System.out.println(customerCodeExternal);
                    if (orderImportRowNum.size() == 0) {
                        docSubmit = XmlUtil.readXML(XmlUtil.toStr(document));
                    }
                    if (i == 0)//第一条选中记录
                    {
                        customerCodePrev = customerCodeExternal;
                        customerNamePrev = customerName;
                        orderIDOriginPrev = orderIDOrigin;
                        orderTypePrve = nc63_Order_type;

                        docSubmit = XmlUtil.readXML(XmlUtil.toStr(document));

                        //nodeOrder.ChildNodes[0].InnerXml = nodeHead.InnerXml;
                        //nodeOrder.ChildNodes[0].ChildNodes[150].InnerXml = NCXML.FormatNC63NodeBody(nodeBody.InnerXml);
                        orderImportRowNum.add(ddmxbhs[i]);
                    } else {
                        if (!customerName.equals(customerNamePrev) || !customerCodePrev.equals(customerCodeExternal) || !orderIDOriginPrev.equals(orderIDOrigin) || !orderTypePrve.equals(nc63_Order_type)) {
                            if (orderImportRowNum.size() > 0) {
                                //CheckMultiCustomer(doc, ref customerCode, customerCodePrev, customerNamePrev, addressPrev);
                                message += PostDataToNC63forYS(XmlUtil.toStr(docSubmit), orderImportRowNum, orderIDOriginPrev, false, startDate);
                            }
                            orderImportRowNum.clear();

                            customerCodePrev = customerCodeExternal;
                            customerNamePrev = customerName;
                            orderIDOriginPrev = orderIDOrigin;
                            orderTypePrve = nc63_Order_type;
                            //addressPrev = ygptAddressName;
                            appendItem(docSubmit, elementBody);
                            //nodeOrder.ChildNodes[0].InnerXml = nodeHead.InnerXml;
                            //nodeOrder.ChildNodes[0].ChildNodes[150].InnerXml = NCXML.FormatNC63NodeBody(nodeBody.InnerXml);
                            orderImportRowNum.add(ddmxbhs[i]);
                            //CheckMultiCustomer(doc, ref customerCode, customerCodePrev, customerNamePrev, addressPrev);
                            //message += PostDataToNC63forYS(XmlUtil.toStr(document), orderImportRowNum,  orderIDOriginPrev, false, startDate);
                        } else {
                            //nodeOrder.ChildNodes[0].ChildNodes[150].InnerXml += NCXML.FormatNC63NodeBody(nodeBody.InnerXml);
                            orderImportRowNum.add(ddmxbhs[i]);
                            if (orderImportRowNum.size() > 1) {
                                appendItem(docSubmit, elementBody);
                            }
                            //CheckMultiCustomer(doc, ref customerCode, customerCodePrev, customerNamePrev, addressPrev);
                            //NodeList nodeList = elementHead.getElementsByTagName("so_saleorder_b");
                            //CommonUtils.XmlSetNodeContent(elementHead,"so_saleorder_b",FormatNC63NodeBody(CommonUtils.XmlGetNodeContent(elementHead,"so_saleorder_b")));
                            if (orderImportRowNum.size() == 10) {
                                docSubmit.normalize();
                                message += PostDataToNC63forYS(XmlUtil.toStr(docSubmit), orderImportRowNum, orderIDOriginPrev, false, startDate);
                                orderImportRowNum.clear();
                            }
                        }
                    }


                } catch (Exception ex) {
                    orderFail.add(ddmxbhs[i]);
                }
            }

            if (orderImportRowNum.size() > 0) {
                //CommonUtils.XmlSetNodeContent(elementHead,"so_saleorder_b",FormatNC63NodeBody(CommonUtils.XmlGetNodeContent(elementHead,"so_saleorder_b")));
                message += PostDataToNC63forYS(XmlUtil.toStr(docSubmit), orderImportRowNum, orderIDOriginPrev, false, startDate);

            }
            String temp = XmlUtil.toStr(document);
            if(StringUtils.isEmpty(message)) {
                return JsonResult.success(message);
            }else {
                return JsonResult.error(message);
            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    /*
    * 配送单和发票传报*/
    @Override
    public JsonResult ExportToYGPT(YgOrderDto dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ003.xml");
        InputStream inputStream03 = classPathResource.getStream();
        //File yq003 = classPathResource.getFile();
        ClassPathResource classPathResource1 = new ClassPathResource("nc/" + "YQ004.xml");
        InputStream inputStream04 = classPathResource1.getStream();
        //File yq004 = classPathResource1.getFile();
        Document document003= XmlUtil.readXML(inputStream03);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        Element elementD = XmlUtil.getElement(elementG,"DETAIL");
        Element YsPsdDetail = XmlUtil.getElement(elementD,"STRUCT");

        Document document004= XmlUtil.readXML(inputStream04);
        Element elementG004=XmlUtil.getRootElement(document004);
        Element YsFpHead = XmlUtil.getElement(elementG004,"HEAD");
        Element YsFpMain = XmlUtil.getElement(elementG004,"MAIN");
        Element elementFpD = XmlUtil.getElement(elementG004,"DETAIL");
        Element YsFpDetail = XmlUtil.getElement(elementFpD,"STRUCT");

        //NodeList YsPsdHead = element.getElementsByTagName("IP");
        String ip = NetUtil.getLocalhostStr();
        String mac = "";
        //发票主键
        String csaleid = "";
        String[] ddmxbhs = dto.getDdmxbhs();
        String czlx = dto.getCzlx();
        String ygtype = dto.getYgtype();
//        boolean upPsd = dto.getUploadPsd();
//        boolean upFp = dto.getUploadFp();
        StringBuilder sb = new StringBuilder();
        YsUploadReuslt result = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsFpHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsFpHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsFpHead,"BZXX","");


        //配送单号
        String psdh = "";
        //金税发票号
        String FaPiao = "";
        String custCode = "";
        String YYBM = "";//医院编码
        String PSDBM = "";//配送点编码
        String orderType = "";//订单类型
        Map<String,String> paramCzlx = new HashMap<>();
        paramCzlx.put("药事新增","1");
        paramCzlx.put("药事修改","2");
        paramCzlx.put("药事作废","3");

        //20191101之前的GPO检查
        String gpo = "";
        String psdRec = ""; //配送单记录条数
        NCInvoice entity = null;
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                entity = ncInvoiceMapper.selectList(new QueryWrapper<NCInvoice>().eq("csaleid", ddmxbhs[i])).get(0);
                psdh = entity.getPsdh()+entity.getCustcode();
                FaPiao = entity.getPsdh();
                csaleid = ddmxbhs[i];
                custCode = entity.getCustcode();
                YYBM = entity.getYybm();
                PSDBM = entity.getPsdbm();
                orderType = entity.getBusiname();
                //阳光配送单XML MAIN 记录 Start
                psdRec = SQLDBQuery.getPsdReco(FaPiao,csaleid);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"CZLX",paramCzlx.get(czlx));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDH",psdh);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"YQBM",Const.YGPT_JGDM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",YYBM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",PSDBM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"CJRQ",DateUtil.format(DateUtils.parseDate(entity.getCjrq()), DatePattern.PURE_DATE_PATTERN));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"SDRQ",DateUtil.format(DateUtils.parseDate(entity.getSdrq()), DatePattern.PURE_DATE_PATTERN));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"ZXS",entity.getZxs());
                CommonUtils.XmlSetNodeContent(YsPsdMain,"JLS",psdRec);
                CommonUtils.XmlSetNodeContent(YsFpHead,"BZXX",entity.getMemo());
                //阳光配送单XML MAIN 记录 end

                //阳光发票XML MAIN 记录 Start
                CommonUtils.XmlSetNodeContent(YsFpMain,"CZLX",paramCzlx.get(czlx));
                CommonUtils.XmlSetNodeContent(YsFpMain,"YQBM",Const.YGPT_JGDM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"YYBM",YYBM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"PSDBM",PSDBM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"JLS",entity.getJls());

                //阳光发票XML MAIN 记录 end

                List<HashMap> rsDt = SQLDBQuery.GetYQ004DetaiListByCsaleid(csaleid);
                String invcode = "";
                String zxspbm = "";
                String errorMessage = "";
                String converRate = "";
                String converRateType = "";

                Document docSubmit003 = null;
                Document docSubmit004 = null;

                //遍历药品明细数据行
                for (int j = 0; j < rsDt.size(); j++) {

                    invcode = rsDt.get(j).get("invcode").toString();
                    zxspbm = rsDt.get(j).get("zxspbm")==null?"":rsDt.get(j).get("zxspbm").toString().trim();
                    if("".equals(zxspbm))
                    {
                        errorMessage+="未能找到发票【"+ FaPiao + "】对应产品【" + invcode + "】，对应的阳光平台统编代码【" + zxspbm + "】，无法进行回传， 请联系关联员！";
                        continue;
                    }
                    //发票数量
                    BigDecimal nnumber = new BigDecimal(rsDt.get(j).get("nnumber").toString());
                    //含税单价
                    BigDecimal ntaxprice = new BigDecimal(rsDt.get(j).get("ntaxprice").toString()).setScale(6,RoundingMode.HALF_UP);
                    //含税金额
                    BigDecimal nsummny = new BigDecimal(rsDt.get(j).get("nsummny").toString());
                    //税率
                    BigDecimal ntaxrate = new BigDecimal(rsDt.get(j).get("ntaxrate").toString());
                    converRate = getFieldValue(rsDt.get(j),"converrate");
                    converRateType = getFieldValue(rsDt.get(j),"converratetype");
                    if(!"".equals(converRate))
                    {
                        if("除".equals(converRateType))
                        {
                            nnumber = nnumber.multiply(new BigDecimal(converRate));
                            ntaxprice = nsummny.divide(nnumber,6,RoundingMode.HALF_UP);
                        }
                        else
                        {
                            nnumber = nnumber.divide(new BigDecimal(converRate));
                            ntaxprice = nsummny.divide(nnumber,6,RoundingMode.HALF_UP);
                        }
                    }
                    else
                    {
                       List<HashMap> convertDt = SQLDBQuery.GetConverRateByZXSPBM(zxspbm);
                       if(convertDt.size()>0)
                       {
                           converRate = getFieldValue(convertDt.get(0),"converrate");
                           converRateType = getFieldValue(convertDt.get(0),"converratetype");
                           if("除".equals(converRateType))
                           {
                               nnumber = nnumber.multiply(new BigDecimal(converRate));
                               ntaxprice = nsummny.divide(nnumber,6,RoundingMode.HALF_UP);
                           }
                           else
                           {
                               nnumber = nnumber.divide(new BigDecimal(converRate));
                               ntaxprice = nsummny.divide(nnumber,6,RoundingMode.HALF_UP);
                           }
                       }
                    }
                    //阳光配送单XML DETAIL 记录 Start
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSDTM",getFieldValue(rsDt.get(j),"psdtm"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"ZXLX",getFieldValue(rsDt.get(j),"zxlx"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SPLX",getFieldValue(rsDt.get(j),"splx"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"ZXSPBM",getFieldValue(rsDt.get(j),"zxspbm"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SCPH",getFieldValue(rsDt.get(j),"cbatchid"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SCRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"dproducedate")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"YXRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"dvalidate")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"XSDDH",getFieldValue(rsDt.get(j),"cinvoice_bid"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"WLPTDDH","");
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"DDMXBH",getFieldValue(rsDt.get(j),"ddmxbh"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSL",nnumber.toString());
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGJLDW",getFieldValue(rsDt.get(j),"cgjldw"));
                    if(j==0)
                    {
                        docSubmit003 = XmlUtil.readXML(XmlUtil.toStr(document003));
                    }
                    //第二行明细开始追加节点
                    if(nsummny.compareTo(BigDecimal.ZERO)>0 && j>0)
                    {
                        appendItem(docSubmit003,YsPsdDetail,"STRUCT");
                    }
                    //阳光配送单XML DETAIL 记录 end

                    //阳光发票 XML DETAIL 记录 Start
                    if("是".equals(entity.getScfph()))
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",entity.getCgoldtaxdm()+FaPiao);
                    }
                    else
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",FaPiao);
                    }
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",FaPiao);
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"dbilldate")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPHSZJE",getFieldValue(rsDt.get(j),"ntotalsummny"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"DLCGBZ","0");
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPBZ","");
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"GLMXBH",getFieldValue(rsDt.get(j),"ddmxbh"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"XSDDH",getFieldValue(rsDt.get(j),"cinvoice_bid"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SPLX",getFieldValue(rsDt.get(j),"splx"));
                    if(Float.parseFloat(getFieldValue(rsDt.get(j),"nsummny"))<0)
                    {
                        ////是否冲红 (是否是由于退货而产生的冲红发票明细；0：否，1：是)
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"SFCH","1");
                    }
                    else
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"SFCH","0");
                    }
                    if ("无法关联".equals(ygtype) && "".equals(getFieldValue(rsDt.get(j),"ddmxbh")))
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"GLBZ","0");
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"WFGLSM",entity.getMemo());
                    }
                    else
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"GLBZ","1");
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"WFGLSM","");
                    }

                    CommonUtils.XmlSetNodeContent(YsFpDetail,"ZXSPBM",zxspbm);
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SCPH",getFieldValue(rsDt.get(j),"cbatchid"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"PZWH",getFieldValue(rsDt.get(j),"graphid"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SPSL",nnumber.toString());
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"CGJLDW",getFieldValue(rsDt.get(j),"cgjldw"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SCRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"dproducedate")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"YXRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"dvalidate")), DatePattern.PURE_DATE_PATTERN));
                    //无税单价 = 含税金额/（1+增值税税率）
                    BigDecimal nprice = BigDecimal.ZERO;
                    try {
                        ntaxrate = ntaxrate.add(BigDecimal.ONE);
                        nprice = ntaxprice.divide(ntaxrate,6, RoundingMode.HALF_UP);
                    }
                    catch(Exception ex)
                    {}

                    CommonUtils.XmlSetNodeContent(YsFpDetail,"WSDJ",nprice.toString());
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"HSDJ",ntaxprice.toString());
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SL",getFieldValue(rsDt.get(j),"ntaxrate"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SE",getFieldValue(rsDt.get(j),"ntaxmny"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"WSJE",getFieldValue(rsDt.get(j),"nmny"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"HSJE",getFieldValue(rsDt.get(j),"nsummny"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"PFJ",ntaxprice.toString());
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"LSJ",ntaxprice.toString());
                    if(j==0)
                    {
                        docSubmit004 = XmlUtil.readXML(XmlUtil.toStr(document004));
                    }
                    if(j>0)
                    {
                        appendItem(docSubmit004,YsFpDetail,"STRUCT");
                    }
                }
                //阳光发票 XML DETAIL 记录 end
                result = YsUploadManual(XmlUtil.toStr(docSubmit003,true),XmlUtil.toStr(docSubmit004,true),csaleid,dto.getUploadPsd(),dto.getUploadFp());
                if(!"0000".equals(result.getCode())) {
                    sb.append(result.getMsg());
                }

            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }

        if("0000".equals(result.getCode())) {
            return JsonResult.success();
        }else{
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult ExportPSDToYGPT(YgOrderDto dto) {
        StringBuilder sbFPXml = new StringBuilder();
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ003.xml");
        InputStream inputStream03 = classPathResource.getStream();
        //File yq003 = classPathResource.getFile();
        ClassPathResource classPathResource1 = new ClassPathResource("nc/" + "YQ004.xml");
        InputStream inputStream04 = classPathResource1.getStream();
        //File yq004 = classPathResource1.getFile();
        Document document003= XmlUtil.readXML(inputStream03);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        Element elementD = XmlUtil.getElement(elementG,"DETAIL");
        Element YsPsdDetail = XmlUtil.getElement(elementD,"STRUCT");

        Document document004= XmlUtil.readXML(inputStream04);
        Element elementG004=XmlUtil.getRootElement(document004);
        Element YsFpHead = XmlUtil.getElement(elementG004,"HEAD");
        Element YsFpMain = XmlUtil.getElement(elementG004,"MAIN");
        Element elementFpD = XmlUtil.getElement(elementG004,"DETAIL");
        Element YsFpDetail = XmlUtil.getElement(elementFpD,"STRUCT");

        //NodeList YsPsdHead = element.getElementsByTagName("IP");
        String ip = NetUtil.getLocalhostStr();
        String mac = "";
        //发票主键
        String csaleid = "";
        String[] ddmxbhs = dto.getDdmxbhs();
        String czlx = dto.getCzlx();
        String ygtype = dto.getYgtype();
//        boolean upPsd = dto.getUploadPsd();
//        boolean upFp = dto.getUploadFp();
        StringBuilder sb = new StringBuilder();
        YsUploadReuslt result = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsFpHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsFpHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsFpHead,"BZXX","");


        //配送单号
        String psdh = "";
        //药事平台配送单编号
        String psdbh = "";
        //金税发票号
        String FaPiao = "";
        String custCode = "";
        String YYBM = "";//医院编码
        String PSDBM = "";//配送点编码
        String orderType = "";//订单类型
        Map<String,String> paramCzlx = new HashMap<>();
        paramCzlx.put("药事新增","1");
        paramCzlx.put("药事修改","2");
        paramCzlx.put("药事作废","3");

        //20191101之前的GPO检查
        String gpo = "";
        String psdRec = ""; //配送单记录条数
        NCDispatching entity = null;
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                entity = dispatchingMapper.selectList(new QueryWrapper<NCDispatching>().eq("ddmxbh", ddmxbhs[i])).get(0);

                psdh = entity.getPsdh();
                psdbh = entity.getPsdbh();

                FaPiao ="";
                csaleid = ddmxbhs[i];
                //custCode = entity.getCustcode();
                YYBM = entity.getYybm();
                PSDBM = entity.getPsdbm();
                //orderType = entity.getBusiname();
                //阳光配送单XML MAIN 记录 Start
                //psdRec = SQLDBQuery.getPsdReco(FaPiao,csaleid);

                CommonUtils.XmlSetNodeContent(YsPsdMain,"CZLX",paramCzlx.get(czlx));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDH",psdh);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBH","");
                CommonUtils.XmlSetNodeContent(YsPsdMain,"YQBM",Const.YGPT_JGDM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",YYBM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",PSDBM);
                CommonUtils.XmlSetNodeContent(YsPsdMain,"CJRQ",DateUtil.format(DateUtils.parseDate(entity.getCjrq()), DatePattern.PURE_DATE_PATTERN));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"SDRQ",DateUtil.format(DateUtils.parseDate(entity.getSdrq()), DatePattern.PURE_DATE_PATTERN));
                CommonUtils.XmlSetNodeContent(YsPsdMain,"ZXS",entity.getZxs());
                CommonUtils.XmlSetNodeContent(YsPsdMain,"JLS",entity.getJls());
                CommonUtils.XmlSetNodeContent(YsFpHead,"BZXX","");
                //阳光配送单XML MAIN 记录 end

                //获取配送单明细及发票明细
                List<HashMap> rsDt = SQLDBQuery.GetSaleInvoiceListByCsaleid(csaleid);

                List<HashMap> rsPsdDetail = SQLDBQuery.GetPsdDetailListByPsdh(psdh);

                //判断配送单YQ004是否已有记录
//                QueryWrapper<YYq004Rs> queryWrapper = new QueryWrapper<>();
//                queryWrapper.select("csaleid");
//                queryWrapper.eq("csaleid",ddmxbhs[i]);
//                List<YYq004Rs> list004= yq004RsMapper.selectList(queryWrapper);
//                if(list004.size()==0) {
//                    YYq004Rs entity004 = new YYq004Rs();
//                    entity004.setCsaleid(entity.getCsaleid());
//                    entity004.setPsdh(entity.getPsdh());
//                    entity004.setCjrq(entity.getCjrq());
//                    entity004.setSdrq(entity.getSdrq());
//                    entity004.setZxs(entity.getZxs());
//                    entity004.setJls(entity.getJls());
//                    entity004.setTs(DateUtils.getTime());
//                    entity004.setStatus("0");
//                    yq004RsMapper.insert(entity004);
//                    //保存明细记录
//                    YYq004RsDetail yq004RsDetail;
//                    for (int k = 0; k < rsPsdDetail.size(); k++) {
//                        yq004RsDetail = new YYq004RsDetail();
//                        yq004RsDetail.setCinvoiceBid(getFieldValue(rsPsdDetail.get(k),"corder_bid"));
//                        yq004RsDetail.setCsaleid(entity.getCsaleid());
//                        yq004RsDetail.setPsdtm(getFieldValue(rsPsdDetail.get(k),"psdtm"));
//                        yq004RsDetail.setZxlx(getFieldValue(rsPsdDetail.get(k),"zxlx"));
//                        yq004RsDetail.setSplx(getFieldValue(rsPsdDetail.get(k),"splx"));
//                        yq004RsDetail.setZxspbm(getFieldValue(rsPsdDetail.get(k),"zxspbm"));
//                        yq004RsDetail.setDdmxbh(getFieldValue(rsPsdDetail.get(k),"ddmxbh"));
//                        yq004RsDetailMapper.insert(yq004RsDetail);
//
//                    }
//
//
//                }


                //阳光发票XML MAIN 记录 Start
                CommonUtils.XmlSetNodeContent(YsFpMain,"CZLX",paramCzlx.get(czlx));
                CommonUtils.XmlSetNodeContent(YsFpMain,"YQBM",Const.YGPT_JGDM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"YYBM",YYBM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"PSDBM",PSDBM);
                CommonUtils.XmlSetNodeContent(YsFpMain,"JLS",String.valueOf(rsDt.size()));
                sbFPXml.append("<MAIN>");
                sbFPXml.append("<CZLX>"+paramCzlx.get(czlx)+"</CZLX>");
                sbFPXml.append("<YQBM>"+Const.YGPT_JGDM+"</YQBM>");
                sbFPXml.append("<YYBM>"+YYBM+"</YYBM>");
                sbFPXml.append("<PSDBM>"+PSDBM+"</PSDBM>");
                sbFPXml.append("<JLS>"+String.valueOf(rsDt.size())+"</JLS>");
                sbFPXml.append("</MAIN>");

                //阳光发票XML MAIN 记录 end

                String invcode = "";
                String zxspbm = "";
                String errorMessage = "";
                String converRate = "";
                String converRateType = "";

                Document docSubmit003 = null;
                Document docSubmit004 = null;

                //遍历药品明细数据行
                sbFPXml.append("<DETAIL>");
                for (int j = 0; j < rsDt.size(); j++) {

                    invcode = rsDt.get(j).get("zxspbm").toString();
                    FaPiao = rsDt.get(j).get("fph").toString();
                    zxspbm = rsDt.get(j).get("zxspbm")==null?"":rsDt.get(j).get("zxspbm").toString().trim();
                    if("".equals(zxspbm))
                    {
                        errorMessage+="未能找到发票【"+ FaPiao + "】对应的阳光平台统编代码【" + zxspbm + "】，无法进行回传， 请联系关联员！";
                        continue;
                    }
                    //发票数量
                    //BigDecimal nnumber = new BigDecimal(rsDt.get(j).get("nnumber").toString());
                    //含税单价
                    BigDecimal ntaxprice = new BigDecimal(rsDt.get(j).get("hsdj").toString()).setScale(6,RoundingMode.HALF_UP);
                    //含税金额
                    BigDecimal nsummny = new BigDecimal(rsDt.get(j).get("hsje").toString());
                    //税率
                    BigDecimal ntaxrate = new BigDecimal(rsDt.get(j).get("sl").toString());

                    //阳光发票 XML DETAIL 记录 Start
/*
                    if("是".equals(entity.getScfph()))
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",entity.getCgoldtaxdm()+FaPiao);
                    }
                    else
                    {
                        CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",FaPiao);
                    }
*/
                    //CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",FaPiao);
                    sbFPXml.append("<STRUCT>");
                    sbFPXml.append("<FPH>"+ FaPiao +"</FPH>");
                    sbFPXml.append("<FPDM>0</FPDM>");
                    sbFPXml.append("<FPHM>"+FaPiao+"</FPHM>");
                    sbFPXml.append("<JYM></JYM>");
                    sbFPXml.append("<FPRQ>"+DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"fprq")), DatePattern.PURE_DATE_PATTERN)+"</FPRQ>");
                    sbFPXml.append("<FPWSZJE>"+getFieldValue(rsDt.get(j),"fpwszje")+"</FPWSZJE>");
                    sbFPXml.append("<FPHSZJE>"+getFieldValue(rsDt.get(j),"fphszje")+"</FPHSZJE>");
                    sbFPXml.append("<DLCGBZ>"+getFieldValue(rsDt.get(j),"dlcgbz")+"</DLCGBZ>");
                    sbFPXml.append("<FPBZ></FPBZ>");
                    sbFPXml.append("<GLMXBH>"+getFieldValue(rsDt.get(j),"glmxbh")+"</GLMXBH>");
                    sbFPXml.append("<XSDDH>"+getFieldValue(rsDt.get(j),"xsddh")+"</XSDDH>");
                    sbFPXml.append("<SPLX>"+getFieldValue(rsDt.get(j),"splx")+"</SPLX>");
                    sbFPXml.append("<SFCH>"+getFieldValue(rsDt.get(j),"sfch")+"</SFCH>");
                    sbFPXml.append("<GLBZ>"+getFieldValue(rsDt.get(j),"glbz")+"</GLBZ>");
                    sbFPXml.append("<WFGLSM>"+getFieldValue(rsDt.get(j),"wfglsm")+"</WFGLSM>");
                    sbFPXml.append("<ZXSPBM>"+getFieldValue(rsDt.get(j),"zxspbm")+"</ZXSPBM>");
                    sbFPXml.append("<SCPH>"+getFieldValue(rsDt.get(j),"scph")+"</SCPH>");
                    sbFPXml.append("<PZWH>"+getFieldValue(rsDt.get(j),"pzwh")+"</PZWH>");
                    sbFPXml.append("<SPSL>"+getFieldValue(rsDt.get(j),"spsl")+"</SPSL>");
                    sbFPXml.append("<CGJLDW>"+getFieldValue(rsDt.get(j),"cgjldw")+"</CGJLDW>");
                    sbFPXml.append("<SCRQ>"+DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"scrq")), DatePattern.PURE_DATE_PATTERN)+"</SCRQ>");
                    sbFPXml.append("<YXRQ>"+DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"yxrq")), DatePattern.PURE_DATE_PATTERN)+"</YXRQ>");
                    sbFPXml.append("<WSDJ>"+getFieldValue(rsDt.get(j),"wsdj")+"</WSDJ>");
                    sbFPXml.append("<HSDJ>"+getFieldValue(rsDt.get(j),"hsdj")+"</HSDJ>");
                    sbFPXml.append("<SL>"+getFieldValue(rsDt.get(j),"sl")+"</SL>");
                    sbFPXml.append("<SE>"+getFieldValue(rsDt.get(j),"se")+"</SE>");
                    sbFPXml.append("<WSJE>"+getFieldValue(rsDt.get(j),"wsje")+"</WSJE>");
                    sbFPXml.append("<HSJE>"+getFieldValue(rsDt.get(j),"hsje")+"</HSJE>");
                    sbFPXml.append("<PFJ>"+getFieldValue(rsDt.get(j),"pfj")+"</PFJ>");
                    sbFPXml.append("<LSJ>"+getFieldValue(rsDt.get(j),"lsj")+"</LSJ>");
                    sbFPXml.append("</STRUCT>");
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPH",FaPiao);
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPHM",FaPiao);
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPDM",getFieldValue(rsDt.get(j),"fpdm"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"JYM","");
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"fprq")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPWSZJE",getFieldValue(rsDt.get(j),"fpwszje"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPHSZJE",getFieldValue(rsDt.get(j),"fphszje"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"DLCGBZ",getFieldValue(rsDt.get(j),"dlcgbz"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"FPBZ","");
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"GLMXBH",getFieldValue(rsDt.get(j),"glmxbh"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"XSDDH",getFieldValue(rsDt.get(j),"xsddh"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SPLX",getFieldValue(rsDt.get(j),"splx"));
                    ////是否冲红 (是否是由于退货而产生的冲红发票明细；0：否，1：是)
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SFCH",getFieldValue(rsDt.get(j),"sfch"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"GLBZ",getFieldValue(rsDt.get(j),"glbz"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"WFGLSM",getFieldValue(rsDt.get(j),"wfglsm"));

                    CommonUtils.XmlSetNodeContent(YsFpDetail,"ZXSPBM",zxspbm);
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SCPH",getFieldValue(rsDt.get(j),"scph"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"PZWH",getFieldValue(rsDt.get(j),"pzwh"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SPSL",getFieldValue(rsDt.get(j),"spsl"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"CGJLDW",getFieldValue(rsDt.get(j),"cgjldw"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SCRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"scrq")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"YXRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(j),"yxrq")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"WSDJ",getFieldValue(rsDt.get(j),"wsdj"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"HSDJ",getFieldValue(rsDt.get(j),"hsdj"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SL",getFieldValue(rsDt.get(j),"sl"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"SE",getFieldValue(rsDt.get(j),"se"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"WSJE",getFieldValue(rsDt.get(j),"wsje"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"HSJE",getFieldValue(rsDt.get(j),"hsje"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"PFJ",getFieldValue(rsDt.get(j),"pfj"));
                    CommonUtils.XmlSetNodeContent(YsFpDetail,"LSJ",getFieldValue(rsDt.get(j),"lsj"));
                    if(j==0)
                    {
                        docSubmit004 = XmlUtil.readXML(XmlUtil.toStr(document004));
                    }
                    if(j>0)
                    {
                        appendItem(docSubmit004,YsFpDetail,"STRUCT");
                    }
                }
                sbFPXml.append("</DETAIL>");
                sbFPXml.append("</XMLDATA>");

                for (int j2 = 0; j2 < rsPsdDetail.size(); j2++) {

                    //阳光配送单XML DETAIL 记录 Start
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSDTM",getFieldValue(rsPsdDetail.get(j2),"psdtm"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"ZXLX",getFieldValue(rsPsdDetail.get(j2),"zxlx"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SPLX",getFieldValue(rsPsdDetail.get(j2),"splx"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"ZXSPBM",getFieldValue(rsPsdDetail.get(j2),"zxspbm"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SCPH",getFieldValue(rsPsdDetail.get(j2),"scph"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"SCRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsPsdDetail.get(j2),"scrq")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"YXRQ",DateUtil.format(DateUtils.parseDate(getFieldValue(rsPsdDetail.get(j2),"yxrq")), DatePattern.PURE_DATE_PATTERN));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"XSDDH",getFieldValue(rsPsdDetail.get(j2),"xsddh"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"WLPTDDH","");
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"DDMXBH",getFieldValue(rsPsdDetail.get(j2),"ddmxbh"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSL",getFieldValue(rsPsdDetail.get(j2),"psl"));
                    CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGJLDW",getFieldValue(rsPsdDetail.get(j2),"cgjldw"));
                    String temp = CommonUtils.XmlGetNodeContent(YsPsdDetail,"PSDTM");
                    if(j2==0)
                    {
                        docSubmit003 = XmlUtil.readXML(XmlUtil.toStr(document003));
                    }
                    //第二行明细开始追加节点
                    if(j2>0)
                    {
                        appendItem(docSubmit003,YsPsdDetail,"STRUCT");
                    }
                    //阳光配送单XML DETAIL 记录 end

                }
                //阳光发票 XML DETAIL 记录 end

                FileUtils.writeLog("",XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()),true));
                result = YsUploadManual(XmlUtil.toStr(docSubmit003,true),XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()),true),csaleid,dto.getUploadPsd(),dto.getUploadFp());
                if(!"0000".equals(result.getCode())) {
                    sb.append(result.getMsg());
                }

            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }

        if(result!=null && "0000".equals(result.getCode())) {
            return JsonResult.success();
        }else{
            return JsonResult.error(sb.toString());
        }
    }


    @Override
    public JsonResult PsdConfirmToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        NCDispatching entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                entity = dispatchingMapper.selectList(new QueryWrapper<NCDispatching>().eq("ddmxbh", ddmxbhs[i])).get(0);

                psdh = entity.getPsdh();
                psdbh = entity.getPsdbh();

                csaleid = ddmxbhs[i];
                //custCode = entity.getCustcode();
                YYBM = entity.getYybm();
                PSDBM = entity.getPsdbm();

                psdXml = getPsdConfirmXml(psdh,psdbh,YYBM,PSDBM,entity.getJls(),csaleid);
                result =YsPsConfirmAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    SQLDBQuery.updateYQ010YgPsState(Const.YG_FP_AND_PS_CONFIRM,csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult FpConfirmToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        NCDispatching entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                entity = dispatchingMapper.selectList(new QueryWrapper<NCDispatching>().eq("ddmxbh", ddmxbhs[i])).get(0);

                psdh = entity.getPsdh();
                psdbh = entity.getPsdbh();

                csaleid = ddmxbhs[i];
                //custCode = entity.getCustcode();
                YYBM = entity.getYybm();
                PSDBM = entity.getPsdbm();

                psdXml = getFpConfirmXml(YYBM,PSDBM,csaleid);
                result =YsFpConfirmAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    //SQLDBQuery.updateYQ010YgFpState(Const.YG_FP_AND_PS_CONFIRM,csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult YQ029ToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        MPruchinvoice entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                csaleid = ddmxbhs[i];
                psdXml = getYQ029Xml(csaleid);
                result =PurchinoviceUploadAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    //SQLDBQuery.updatePruchinvoiceFpState("10",csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult YQ031ToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        MPruchinvoice entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                csaleid = ddmxbhs[i];
                psdXml = getYQ031Xml(csaleid);
                result =InoviceRelationUploadAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    //SQLDBQuery.updatePruchinvoiceFpState("10",csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult YQ032ToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        MPruchinvoice entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                csaleid = ddmxbhs[i];
                psdXml = getYQ032Xml(csaleid);
                result =InoviceRelationConfirmAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    //SQLDBQuery.updatePruchinvoiceFpState("10",csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    @Override
    public JsonResult YQ030ToYGPT(YgOrderDto dto) {
        String[] ddmxbhs = dto.getDdmxbhs();
        MPruchinvoice entity;
        String psdh="";
        String psdbh="";
        String csaleid="";
        String YYBM="";
        String PSDBM="";
        String psmxts;
        String psdXml = "";
        String[] result = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddmxbhs.length; i++) {
            try {
                csaleid = ddmxbhs[i];
                psdXml = getYQ030Xml(csaleid);
                result =PurchinoviceConfirmAuto(psdXml,csaleid);
                if ("00000".equals(result[4])) {
                    //SQLDBQuery.updatePruchinvoiceFpState("10",csaleid);
                } else {
                    sb.append(result[4]+result[5]+":"+result[6]);
                }


            }
            catch(Exception ex)
            {
                sb.append(ex.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString()))
        {
            return JsonResult.success();
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }

    /*
    * 阳光平台订单响应
    * */
    @Override
    public JsonResult OrderResponseToYGPT(YgOrderDto dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ039.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        Element elementD = XmlUtil.getElement(elementG,"DETAIL");
        Element YsPsdDetail = XmlUtil.getElement(elementD,"STRUCT");
        String[] ddmxbhs = dto.getDdmxbhs();
        String xylx = dto.getCzlx();
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"JLS",String.valueOf(ddmxbhs.length));
        for (int i = 0; i < ddmxbhs.length; i++) {
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"DDMXBH",ddmxbhs[i]);
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSCLBS",xylx);
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"PSCLSM","");
            if(i==0) {
                docSubmit003 = XmlUtil.readXML(XmlUtil.toStr(document003));
            } else {
                appendItem(docSubmit003,YsPsdDetail,"STRUCT");
            }

        }
        try {
            result = YsOrderResponse(XmlUtil.toStr(docSubmit003, true), ddmxbhs, xylx);
            if ("00000".equals(result[4])) {
                return JsonResult.success();
            } else {
                return JsonResult.error(result[4]+result[5]+":"+result[6]);
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }


    private String getPsdConfirmXml(String psdh, String psdbh, String yybm, String psdbm, String psmxts, String csaleid)
    {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ040.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBH",psdbh);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDH",psdh);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YQBM",Const.YGPT_JGDM);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",yybm);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",psdbm);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSMXTS",psmxts);

        return XmlUtil.toStr(document003, true);
    }

    /*
     * 获取发票提交报文
     * */
    private String getFpConfirmXml(String yybm, String psdbm, String csaleid)
    {
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;
        StringBuilder sbFPXml = new StringBuilder();
        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        List<HashMap> rsDt = new ArrayList<>();
        try {
            rsDt = SQLDBQuery.GetSaleInvoiceListByCsaleid(csaleid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        sbFPXml.append("<MAIN>");
        sbFPXml.append("<YQBM>"+Const.YGPT_JGDM+"</YQBM>");
        sbFPXml.append("<YYBM>"+yybm+"</YYBM>");
        sbFPXml.append("<PSDBM>"+psdbm+"</PSDBM>");
        sbFPXml.append("<JLS>"+String.valueOf(rsDt.size())+"</JLS>");
        sbFPXml.append("</MAIN>");

        sbFPXml.append("<DETAIL>");
        String FaPiao="";
        for (int i = 0; i < rsDt.size(); i++) {
            FaPiao = getFieldValue(rsDt.get(i),"fph");
            sbFPXml.append("<STRUCT>");
            sbFPXml.append("<FPH>"+ FaPiao +"</FPH>");
            sbFPXml.append("<FPDM>0</FPDM>");
            sbFPXml.append("<FPHM>"+FaPiao+"</FPHM>");
            sbFPXml.append("<FPRQ>"+DateUtil.format(DateUtils.parseDate(getFieldValue(rsDt.get(i),"fprq")), DatePattern.PURE_DATE_PATTERN)+"</FPRQ>");
            sbFPXml.append("</STRUCT>");
        }
        sbFPXml.append("</DETAIL>");
        sbFPXml.append("</XMLDATA>");
        return XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()), true);
    }

    /*
    * 获取进货发票信息传报报文
    * */
    private String getYQ029Xml(String csaleid)
    {
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;
        StringBuilder sbFPXml = new StringBuilder();
        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        DinvoiceInfo entity = invoiceInfoMapper.selectById(csaleid);
        List<DinvoiceDetailInfo> rsDt = invoiceInfoMapper.getPOInvoiceDetailList(csaleid);

        sbFPXml.append("<MAIN>");
        sbFPXml.append("<FPDM>"+entity.getVinvoicedm()+"</FPDM>");
        sbFPXml.append("<FPH>"+entity.getVinvoicecode()+"</FPH>");
        sbFPXml.append("<FPRQ>"+DateUtil.format(entity.getDinvoicedate(), DatePattern.PURE_DATE_PATTERN)+"</FPRQ>");
        sbFPXml.append("<FPKJFMC>"+entity.getCustname()+"</FPKJFMC>");
        sbFPXml.append("<FPJSFMC>"+Const.CORP_NAME+"</FPJSFMC>");
        sbFPXml.append("<BZSM></BZSM>");
        sbFPXml.append("<JLS>"+String.valueOf(rsDt.size())+"</JLS>");
        sbFPXml.append("</MAIN>");

        sbFPXml.append("<DETAIL>");
        String FaPiao="";
        for (int i = 0; i < rsDt.size(); i++) {
            sbFPXml.append("<STRUCT>");
            sbFPXml.append("<SXH>"+ rsDt.get(i).getSxh() +"</SXH>");
            sbFPXml.append("<ZXSPBM>"+rsDt.get(i).getZxspbm()+"</ZXSPBM>");
            sbFPXml.append("<SCPH>"+rsDt.get(i).getVproducenum()+"</SCPH>");
            sbFPXml.append("</STRUCT>");
        }
        sbFPXml.append("</DETAIL>");
        sbFPXml.append("</XMLDATA>");
        return XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()), true);
    }


    /*
     * 获取进货发票信息传报报文
     * */
    private String getYQ030Xml(String csaleid)
    {
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;
        StringBuilder sbFPXml = new StringBuilder();
        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        DinvoiceInfo entity = invoiceInfoMapper.selectById(csaleid);
        List<DinvoiceDetailInfo> rsDt = invoiceInfoMapper.getPOInvoiceDetailList(csaleid);

        sbFPXml.append("<MAIN>");
        sbFPXml.append("<FPID>"+entity.getFpid()+"</FPID>");
        sbFPXml.append("<FPDM>"+entity.getVinvoicedm()+"</FPDM>");
        sbFPXml.append("<FPH>"+entity.getVinvoicecode()+"</FPH>");
        sbFPXml.append("<FPMXS>"+String.valueOf(rsDt.size())+"</FPMXS>");
        sbFPXml.append("</MAIN>");
        sbFPXml.append("</XMLDATA>");
        return XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()), true);
    }

    /*
     * 获取配送发票与进货发票关联关系传报报文
     * */
    private String getYQ031Xml(String csaleid)
    {
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;
        StringBuilder sbFPXml = new StringBuilder();
        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        Map<String,Object> param = new HashMap<>();
        param.put("businessid",csaleid);
        List<MInvoicesrelation> list = invoicesrelationMapper.selectByMap(param);
        MInvoicesrelation entity = list.get(0);
        List<MInvoicesrelationline> rsDt = invoicesrelationlineMapper.selectList(new QueryWrapper<MInvoicesrelationline>().eq("relationbusinessid",csaleid));

        sbFPXml.append("<MAIN>");
        sbFPXml.append("<FPH>"+entity.getSalesfph()+"</FPH>");
        sbFPXml.append("<FPDM>0</FPDM>");
        sbFPXml.append("<FPHM>"+entity.getSalesfph()+"</FPHM>");
        sbFPXml.append("<FPRQ>"+DateUtil.format(DateUtils.parseDate(entity.getSalesfprq()), DatePattern.PURE_DATE_PATTERN)+"</FPRQ>");
        sbFPXml.append("<FPHSJE>"+entity.getSalesfphsje()+"</FPHSJE>");
        sbFPXml.append("<JLS>"+String.valueOf(rsDt.size())+"</JLS>");
        sbFPXml.append("</MAIN>");

        sbFPXml.append("<DETAIL>");
        String FaPiao="";
        for (int i = 0; i < rsDt.size(); i++) {
            sbFPXml.append("<STRUCT>");
            sbFPXml.append("<SXH>"+ (i+1) +"</SXH>");
            sbFPXml.append("<FPDM>"+rsDt.get(i).getPruchfpdm()+"</FPDM>");
            sbFPXml.append("<FPH>"+rsDt.get(i).getPruchfph()+"</FPH>");
            sbFPXml.append("</STRUCT>");
        }
        sbFPXml.append("</DETAIL>");
        sbFPXml.append("</XMLDATA>");
        return XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()), true);
    }

    /*
     * 获取配送发票与进货发票关联关系确认报文
     * */
    private String getYQ032Xml(String csaleid)
    {
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;
        StringBuilder sbFPXml = new StringBuilder();
        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sbFPXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sbFPXml.append("<XMLDATA>");
        sbFPXml.append("<HEAD>");
        sbFPXml.append("<IP>"+ip+"</IP>");
        sbFPXml.append("<MAC>"+mac.replaceAll(":","").replaceAll("-","")+"</MAC>");
        sbFPXml.append("<BZXX></BZXX>");
        sbFPXml.append("</HEAD>");
        Map<String,Object> param = new HashMap<>();
        param.put("businessid",csaleid);
        List<MInvoicesrelation> list = invoicesrelationMapper.selectByMap(param);
        MInvoicesrelation entity = list.get(0);
        List<MInvoicesrelationline> rsDt = invoicesrelationlineMapper.selectList(new QueryWrapper<MInvoicesrelationline>().eq("relationbusinessid",csaleid));

        sbFPXml.append("<MAIN>");
        sbFPXml.append("<GLID>"+entity.getGlid()+"</GLID>");
        sbFPXml.append("<FPH>"+entity.getSalesfph()+"</FPH>");
        sbFPXml.append("<FPDM>0</FPDM>");
        sbFPXml.append("<FPHM>"+entity.getSalesfph()+"</FPHM>");
        sbFPXml.append("<FPRQ>"+DateUtil.format(DateUtils.parseDate(entity.getSalesfprq()), DatePattern.PURE_DATE_PATTERN)+"</FPRQ>");
        sbFPXml.append("<FPHSJE>"+entity.getSalesfphsje()+"</FPHSJE>");
        sbFPXml.append("<GLFPS>"+String.valueOf(rsDt.size())+"</GLFPS>");
        sbFPXml.append("</MAIN>");
        sbFPXml.append("</XMLDATA>");
        return XmlUtil.toStr(XmlUtil.readXML(sbFPXml.toString()), true);
    }


    private YsUploadReuslt YsUploadManual(String YsPsdXml, String YsFpXml, String csaleid, boolean upPsd, boolean upFp) throws SQLException {
        //阳光配送单传报
        String[] retPsd = new String[7];
        String[] retFp = new String[7];
        if(upPsd)
        {
            retPsd =  YsPsUploadAuto(YsPsdXml,csaleid);
            if("00000".equals(retPsd[4]))
            {
                //retPsd = YsPsConfirmAuto(YsPsdXml,csaleid);
            }
        }
        if(upFp)
        {
            retFp = YsFpUploadAuto(YsFpXml,csaleid);
            if("00000".equals(retFp[4]))
            {
                //retFp = YsFpConfirmAuto(YsFpXml,csaleid);
            }
        }
        //YsUploadReuslt reuslt = new YsUploadReuslt();
        if("00000".equals(retPsd[4]) && "00000".equals(retFp[4])) {
            return YsUploadReuslt.builder().code("00000").msg("发票上传成功").build();
        }
        else {
            String message = "";
            if(upPsd) {
                message = ObjectUtil.isNull(retPsd[5]) ? "" : retPsd[5];
            }
            if(upFp) {
                message += ObjectUtil.isNull(retFp[5]) ? "" : retFp[5];
                message += ObjectUtil.isNull(retFp[6]) ? "" : retFp[6];
            }
            return YsUploadReuslt.builder().code("0001").msg(message).build();
        }






    }
    public String[] YsOrderResponse(String YsXml,String[] ddmxbhs,String xylx) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ039", YsXml);
        String ddmxbh = "";
        if ("00000".equals(rtnPsd[4]) || ("20000".equals(rtnPsd[4]) && rtnPsd[6].contains("已响应")))
        {
            for (int i = 0; i < ddmxbhs.length; i++) {
                //更新订单响应类型
                SQLDBQuery.updateYQ039YgddXylx(xylx, ddmxbhs[i]);
                //写入阳光配送单的日志
                SQLDBQuery.insertOrderTrackDetail(ddmxbhs[i], Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_03_07 + "," + "成功！");
            }
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, "", Const.YQ039_TXT);
        return rtnPsd;
    }


    public String[] YsPsUploadAuto(String YsPsXml, String csaleid) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ003", YsPsXml);
        if ("00000".equals(rtnPsd[4]) || ("12019".equals(rtnPsd[4]) && rtnPsd[5].contains("已存在")&& rtnPsd[5].contains("配送单")))
        {
            //更新配送单编号
            String psdbh = "";
            String psmxbh = "";
            String psdtm = "";
            String scph="";
            String xsddh = "";
            Document document003= XmlUtil.readXML(rtnPsd[2]);
            Element elementG=XmlUtil.getRootElement(document003);
            Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
            Element YsPsdDetail = XmlUtil.getElement(elementG,"DETAIL");
            psdbh = CommonUtils.XmlGetNodeContent(YsPsdMain,"PSDBH");
            SQLDBQuery.updateYQ010YgPsdbh(psdbh, csaleid);
            Element detailStruct;
//            for (int i = 0; i < YsPsdDetail.getChildNodes().getLength(); i++) {
//                detailStruct =(Element) YsPsdDetail.getChildNodes().item(i);
//                psmxbh = CommonUtils.XmlGetNodeContent(detailStruct,"PSMXBH");
//                psdtm = CommonUtils.XmlGetNodeContent(detailStruct,"PSDTM");
//                scph = CommonUtils.XmlGetNodeContent(detailStruct,"SCPH");
//                xsddh = CommonUtils.XmlGetNodeContent(detailStruct,"XSDDH");
//                SQLDBQuery.updateYQ004YgPsmxbh(psdbh, csaleid,psdtm,scph,xsddh);
//            }

            //更新状态为已上传
            SQLDBQuery.updateYQ010YgPsState(Const.YG_FP_AND_PS_OK, csaleid);
            //写入阳光配送单的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_03_01 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, csaleid, Const.YQ003_TXT);
        return rtnPsd;
    }

    public String[] YsPsConfirmAuto(String YsPsXml, String csaleid) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ040", YsPsXml);
        if ("00000".equals(rtnPsd[4]) || ("12019".equals(rtnPsd[4]) && rtnPsd[5].contains("已存在")&& rtnPsd[5].contains("配送单")))
        {
            //更新状态为已上传
            SQLDBQuery.updateYQ010YgPsState(Const.YG_FP_AND_PS_CONFIRM, csaleid);
            //写入阳光配送单的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_03_08 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, csaleid, Const.YQ040_TXT);
        return rtnPsd;
    }

    public String[] YsFpUploadAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ004", YsFpXml);
        //更新状态为已上传
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传
            SQLDBQuery.updateYQ010YgFpState(Const.YG_FP_AND_PS_OK, csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_02 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ004_TXT);
        return rtnFp;
    }

    public String[] YsFpConfirmAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ041", YsFpXml);
        //更新状态为已上传
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传
            SQLDBQuery.updateYQ010YgFpState(Const.YG_FP_AND_PS_CONFIRM, csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_09 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ041_TXT);
        return rtnFp;
    }

    public String[] PurchinoviceUploadAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ029", YsFpXml);
        //更新状态为已上传
        Document document003= XmlUtil.readXML(rtnFp[2]);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        String cwxx = rtnFp[5];
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传，同时更新药事平台返回的发票ID
            String fpid = CommonUtils.XmlGetNodeContent(YsPsdMain,"FPID");
            SQLDBQuery.updatePruchinvoiceFpState("1",fpid, cwxx,csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_10 + "," + "成功！");
        }else{
            SQLDBQuery.updatePruchinvoiceFpState("0","",cwxx, csaleid);
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ029_TXT);
        return rtnFp;
    }

    public String[] PurchinoviceConfirmAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ030", YsFpXml);
        //更新状态为已上传
        String cwxx = rtnFp[5];
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传
            SQLDBQuery.updatePruchinvoiceFpState("2","",cwxx, csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_11 + "," + "成功！");
        }else{
            SQLDBQuery.updatePruchinvoiceFpState("1","",cwxx, csaleid);
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ030_TXT);
        return rtnFp;
    }


    public String[] InoviceRelationUploadAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ031", YsFpXml);
        //更新状态为已上传
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传，同时更新药事平台返回的发票ID
            Document document003= XmlUtil.readXML(rtnFp[2]);
            Element elementG=XmlUtil.getRootElement(document003);
            Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
            String fpid = CommonUtils.XmlGetNodeContent(YsPsdMain,"GLID");

            SQLDBQuery.updateInvoiceRelationFpState("10",fpid, csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_12 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ031_TXT);
        return rtnFp;
    }

    public String[] InoviceRelationConfirmAuto(String YsFpXml, String csaleid) throws SQLException {
        //阳光发票传报
        String[] rtnFp = YsIntfce.SendYgRecv2019("YQ032", YsFpXml);
        //更新状态为已上传
        if ("00000".equals(rtnFp[4]) || ("10000".equals(rtnFp[4]) && (rtnFp[6].contains("已存在") && rtnFp[6].contains("发票号"))))
        {
            //更新状态为已上传
            SQLDBQuery.updateInvoiceRelationFpState("20","", csaleid);
            //写入阳光阳光发票的日志
            SQLDBQuery.insertOrderTrackDetail(csaleid, Const.ORDER_03, DateUtil.now() + " " + Const.ORDER_03_13 + "," + "成功！");
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnFp, csaleid, Const.YQ032_TXT);
        return rtnFp;
    }

    private String getFieldValue(HashMap map,String key)
    {
        return map.get(key)==null?"":map.get(key).toString();
    }

    private void appendItem(Document document, Element src)
    {
        NodeList itemList = src.getChildNodes();
        Element elementItem =  document.createElement("item");
        for (int i = 0; i < itemList.getLength(); i++) {
            if(XmlUtil.isElement(itemList.item(i))) {
                Element ele = document.createElement(itemList.item(i).getNodeName());
                Text txtNode = document.createTextNode(itemList.item(i).getTextContent());
                ele.appendChild(txtNode);
                elementItem.appendChild(ele);
            }
        }
        Element elementG=XmlUtil.getRootElement(document);
        Element elementBill =XmlUtil.getElement(elementG,"bill");
        Element elementHead =XmlUtil.getElement(elementBill,"billhead");

        Element elementDetail =XmlUtil.getElement(elementHead,"so_saleorder_b");
        elementDetail.appendChild(elementItem);

    }

    private void appendItem(Document document, Element src,String elementName)
    {
        NodeList itemList = src.getChildNodes();
        Element elementItem =  document.createElement(elementName);
        for (int i = 0; i < itemList.getLength(); i++) {
            if(XmlUtil.isElement(itemList.item(i))) {
                Element ele = document.createElement(itemList.item(i).getNodeName());
                Text txtNode = document.createTextNode(itemList.item(i).getTextContent());
                ele.appendChild(txtNode);
                elementItem.appendChild(ele);
            }
        }
        Element elementG=XmlUtil.getRootElement(document);
        Element elementDetail =XmlUtil.getElement(elementG,"DETAIL");
        elementDetail.appendChild(elementItem);

    }

    public static String xmlToJson(String xmlStr) {
        // 将XML字符串转为Hutool的XML对象
        // 调用Hutool的JSON工具类，将XML转为JSON字符串
        Document doc = XmlUtil.readXML(xmlStr);
        String jsonStr = JSONUtil.toJsonStr(doc);

        return jsonStr;
    }

    public String innerXml(Node node) {
        DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
        LSSerializer lsSerializer = lsImpl.createLSSerializer();
        NodeList childNodes = node.getChildNodes();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < childNodes.getLength(); i++) {
            sb.append(lsSerializer.writeToString(childNodes.item(i)));
        }
        return sb.toString();
    }
}
